# -*- coding: utf-8 -*-
"""
# --------------------------------------------------------
# @Author : Pan
# @E-mail : 
# @Date   : 2025-11-13 10:38:52
# @Brief  :
# --------------------------------------------------------
"""
from PIL import Image

from modelscope import Qwen3VLForConditionalGeneration, AutoProcessor
from pybaseutils import image_utils, file_utils

# 图像数量必须在 4 到 512 张之间（Qwen3-VL 和 Qwen2.5-VL 的要求）
# 如果你从视频流中实时抽帧，建议控制帧率（如每秒 2 帧），避免超过 512 帧上限。Qwen 系列默认以 2 FPS 对视频抽帧
image_dir = "/home/PKing/nasdata/Project/LLM/MLLM-Factory/data/video1-frame"
image_list = file_utils.get_files_lists(image_dir)
frames = [Image.open(file) for file in image_list]

# default: Load the model on the available device(s)
model_file = "/home/PKing/nasdata/Project/LLM/models/Qwen/Qwen3-VL-2B-Instruct"
model = Qwen3VLForConditionalGeneration.from_pretrained(model_file, dtype="auto", device_map="cuda")

# We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.
# model = Qwen3VLForConditionalGeneration.from_pretrained(
#     "Qwen/Qwen3-VL-4B-Instruct",
#     dtype=torch.bfloat16,
#     attn_implementation="flash_attention_2",
#     device_map="auto",
# )


processor = AutoProcessor.from_pretrained(model_file)

messages = [
    {
        "role": "user",
        "content": [
            {"type": "video", "video": frames},
            {"type": "text", "text": "请描述这个视频"},
        ],
    }
]

# Preparation for inference
inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
    return_tensors="pt",
).to('cuda')

# Inference: Generation of the output
generated_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids_trimmed = [
    out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
output_text = processor.batch_decode(
    generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print(output_text)
